from vnpy.trader.ui import QtWidgets
from vnpy.trader.engine import MainEngine
from vnpy.trader.constant import Direction, Offset, OrderType
from vnpy.trader.object import OrderRequest


class MultiGatewayWidget(QtWidgets.QWidget):
    """多接口下单交易组件"""

    def __init__(self, main_engine: MainEngine) -> None:
        """构造函数"""
        super().__init__()

        self.main_engine: MainEngine = main_engine

        self.init_ui()

    def init_ui(self) -> None:
        """初始化界面"""
        self.setWindowTitle("多账号同步委托")

        self.symbol_line = QtWidgets.QLineEdit()
        self.price_line = QtWidgets.QLineEdit()
        self.volume_line = QtWidgets.QLineEdit()

        self.direction_combo = QtWidgets.QComboBox()
        self.direction_combo.addItems([d.value for d in Direction])

        self.offset_combo = QtWidgets.QComboBox()
        self.offset_combo.addItems([o.value for o in Offset])

        button = QtWidgets.QPushButton("委托")
        button.clicked.connect(self.send_order)

        form = QtWidgets.QFormLayout()
        form.addRow("本地代码", self.symbol_line)
        form.addRow("方向", self.direction_combo)
        form.addRow("开平", self.offset_combo)
        form.addRow("价格", self.price_line)
        form.addRow("数量", self.volume_line)
        form.addRow(button)

        self.setLayout(form)

    def send_order(self) -> None:
        """委托下单"""
        vt_symbol = self.symbol_line.text()
        contract = self.main_engine.get_contract(vt_symbol)
        if not contract:
            return

        req = OrderRequest(
            symbol=contract.symbol,
            exchange=contract.exchange,
            direction=Direction(self.direction_combo.currentText()),
            offset=Offset(self.offset_combo.currentText()),
            price=float(self.price_line.text()),
            volume=int(self.volume_line.text()),
            type=OrderType.LIMIT
        )

        for gateway_name in self.main_engine.get_all_gateway_names():
            self.main_engine.send_order(req, gateway_name)
